package cn.z2huo.knowledge.concurrency.aqs;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;

/**
 * <p>
 *
 * @author z2huo
 */
class SimpleMockLockTest {

    /**
     * 线程数量
     */
    private static final int THREAD_COUNT = 10;

    /**
     * 循环次数
     */
    private static final int TURNS = 1000000;

    public static void main(String[] args) {

        ExecutorService threadPool = Executors.newFixedThreadPool(10);

        Lock lock = new SimpleMockLock();

        CountDownLatch countDownLatch = new CountDownLatch(THREAD_COUNT);

        long start, end;

        start = System.currentTimeMillis();
        // 10 个线程并发执行
        for (int i = 0; i < THREAD_COUNT; i++) {
            threadPool.submit(() -> {
                try {
                    // 累加
                    for (int j = 0; j < TURNS; j++) {
                        // 加锁累加
                        IncrementData.lockAndFastIncrease(lock);
                        // 不加锁累加
//                        IncrementData.increase();
                    }
                    System.out.println(Thread.currentThread().getName() +" 本线程累加完成");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 线程执行完毕，倒数门闩减少一次
                countDownLatch.countDown();
            });
        }

        try {
            // 等待所有线程执行完成，所有线程结束
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        end = System.currentTimeMillis();

        System.out.println("总耗时：" + (end - start) + " ms");
        System.out.println("累加结果为 " + IncrementData.sum);

        threadPool.close();
    }

}
